<template>
  <div class="student-management">
    <div class="page-header">
      <h2>学生管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加学生
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="学号">
          <el-input 
            v-model="searchForm.studentId" 
            placeholder="请输入学号"
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入学生姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="专业">
          <el-input 
            v-model="searchForm.major" 
            placeholder="请输入专业"
            clearable
          />
        </el-form-item>
        <el-form-item label="年级">
          <el-input 
            v-model="searchForm.grade" 
            placeholder="请输入年级"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="realName" label="姓名" width="100" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="department" label="院系" width="150" />
        <el-table-column prop="major" label="专业" width="120" />
        <el-table-column prop="grade" label="年级" width="80" />
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'">
              {{ row.enabled ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="成果统计" width="120">
          <template #default="{ row }">
            <el-tooltip content="点击查看详细统计" placement="top">
              <el-button type="text" @click="handleViewStats(row)">
                {{ row.totalAchievements || 0 }} 项
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" @click="handleViewAchievements(row)">
              查看成果
            </el-button>
            <el-button 
              type="text" 
              @click="handleToggleStatus(row)"
              :style="{ color: row.enabled ? '#f56c6c' : '#67c23a' }"
            >
              {{ row.enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="text" 
              @click="handleDelete(row)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 学生表单对话框 -->
    <el-dialog 
      v-model="formDialogVisible" 
      :title="isEdit ? '编辑学生信息' : '添加学生'" 
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input 
                v-model="form.studentId" 
                placeholder="请输入学号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input 
                v-model="form.realName" 
                placeholder="请输入学生姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEdit">
            <el-form-item label="初始密码" prop="password">
              <el-input 
                v-model="form.password" 
                type="password"
                placeholder="请输入初始密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="form.email" 
                placeholder="请输入邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="form.phone" 
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院系" prop="department">
              <el-input 
                v-model="form.department" 
                placeholder="请输入院系"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input 
                v-model="form.major" 
                placeholder="请输入专业"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-input 
                v-model="form.grade" 
                placeholder="请输入年级"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="enabled">
              <el-switch 
                v-model="form.enabled"
                active-text="正常"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 成果统计对话框 -->
    <el-dialog 
      v-model="statsDialogVisible" 
      title="学生成果统计" 
      width="500px"
    >
      <div v-if="currentStudent" class="stats-content">
        <div class="student-info">
          <h4>{{ currentStudent.realName }}（{{ currentStudent.studentId }}）</h4>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ studentStats.verticalProjects }}</div>
              <div class="stat-label">纵向课题</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ studentStats.horizontalProjects }}</div>
              <div class="stat-label">横向课题</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number">{{ studentStats.papers }}</div>
              <div class="stat-label">学术论文</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number pending">{{ studentStats.pending }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number approved">{{ studentStats.approved }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number rejected">{{ studentStats.rejected }}</div>
              <div class="stat-label">已拒绝</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { userAPI } from '@/api/user'

export default {
  name: 'StudentManagement',
  components: {
    Plus,
    Search,
    Refresh
  },
  setup() {
    const router = useRouter()
    
    const loading = ref(false)
    const saving = ref(false)
    const tableData = ref([])
    const formDialogVisible = ref(false)
    const statsDialogVisible = ref(false)
    const formRef = ref()
    const isEdit = ref(false)
    const currentStudent = ref(null)
    
    const searchForm = reactive({
      studentId: '',
      realName: '',
      major: '',
      grade: ''
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const form = reactive({
      studentId: '',
      realName: '',
      username: '',
      password: 'password',
      email: '',
      phone: '',
      department: '',
      major: '',
      grade: '',
      enabled: true
    })
    
    const studentStats = reactive({
      verticalProjects: 0,
      horizontalProjects: 0,
      papers: 0,
      pending: 0,
      approved: 0,
      rejected: 0
    })
    
    const rules = reactive({
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入学生姓名', trigger: 'blur' }
      ],
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入初始密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ]
    })
    
    // 编辑时不需要密码验证
    const editRules = computed(() => {
      const editRulesObj = { ...rules }
      delete editRulesObj.password
      return editRulesObj
    })
    
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage - 1,
          size: pagination.pageSize,
          role: 'STUDENT',
          ...searchForm
        }
        
        const response = await userAPI.getUsersByRole('STUDENT', params)
        tableData.value = response.data.content || []
        pagination.total = response.data.totalElements || 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = () => {
      pagination.currentPage = 1
      loadData()
    }
    
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      pagination.currentPage = 1
      loadData()
    }
    
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadData()
    }
    
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadData()
    }
    
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      formDialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      isEdit.value = true
      Object.keys(form).forEach(key => {
        if (row[key] !== undefined) {
          form[key] = row[key]
        }
      })
      formDialogVisible.value = true
    }
    
    const handleSave = async () => {
      try {
        await formRef.value.validate()
        
        saving.value = true
        
        if (isEdit.value) {
          await userAPI.updateUser(form.id, form)
          ElMessage.success('更新成功')
        } else {
          await userAPI.createUser(form, 'STUDENT')
          ElMessage.success('创建成功')
        }
        
        formDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
    
    const handleToggleStatus = async (row) => {
      try {
        await userAPI.toggleUserStatus(row.id)
        ElMessage.success(row.enabled ? '禁用成功' : '启用成功')
        loadData()
      } catch (error) {
        console.error('状态切换失败:', error)
        ElMessage.error('状态切换失败')
      }
    }
    
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个学生吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await userAPI.deleteUser(row.id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleViewStats = async (row) => {
      currentStudent.value = row
      try {
        // TODO: 调用API获取学生成果统计
        // const response = await userAPI.getStudentStats(row.id)
        // Object.assign(studentStats, response.data)
        
        // 模拟数据
        Object.assign(studentStats, {
          verticalProjects: 3,
          horizontalProjects: 2,
          papers: 5,
          pending: 1,
          approved: 8,
          rejected: 1
        })
        
        statsDialogVisible.value = true
      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.error('获取统计数据失败')
      }
    }
    
    const handleViewAchievements = (row) => {
      // 跳转到成果列表页面，并筛选该学生的成果
      router.push({
        path: '/vertical-projects/list',
        query: { userId: row.id }
      })
    }
    
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (key === 'enabled') {
          form[key] = true
        } else if (key === 'password') {
          form[key] = 'password'
        } else {
          form[key] = ''
        }
      })
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      saving,
      tableData,
      searchForm,
      pagination,
      formDialogVisible,
      statsDialogVisible,
      formRef,
      isEdit,
      currentStudent,
      form,
      studentStats,
      rules: computed(() => isEdit.value ? editRules.value : rules),
      loadData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleSave,
      handleToggleStatus,
      handleDelete,
      handleViewStats,
      handleViewAchievements
    }
  }
}
</script>

<style lang="scss" scoped>
.student-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .stats-content {
    .student-info {
      text-align: center;
      margin-bottom: 20px;
      
      h4 {
        margin: 0;
        color: #303133;
      }
    }
    
    .stat-item {
      text-align: center;
      padding: 20px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #409eff;
        line-height: 1;
        
        &.pending {
          color: #e6a23c;
        }
        
        &.approved {
          color: #67c23a;
        }
        
        &.rejected {
          color: #f56c6c;
        }
      }
      
      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-top: 8px;
      }
    }
  }
}
</style>
